import React, { Component } from 'react';
import { Route, Switch, BrowserRouter as Router, Redirect } from 'react-router-dom'; // 路由
import { ConfigProvider } from 'antd';
import { util, pubsub } from './utils';
import { routes } from './routes.config';
import { userService } from './server';
import { inject, observer } from 'mobx-react';
import { config } from './config';

@inject('user')
@observer
class Routers extends Component {
  constructor(props) {
    super(props);
    this.state = {
      keyid: util.randomID()
    };
    this.routerRef = React.createRef();
  }

  componentDidMount() {
    const { history } = this.routerRef.current;
    util.history = history;

    const p = window.location.pathname.split('/')[1];
    const [data] = routes.filter(route => route.path === '/' + p);

    // 如果url存在token
    let token = util.getUrlQuery('token');
    if (token) {
      // 去掉url对应的token参数
      this.props.history.pushState(null, null, util.delUrlParam('token'));
      token = decodeURI(token);
      userService.setToken(token);
      user.setToken(token);
    }
    if (data && data?.meta?.auth) {
      // 需要登录
      userService.getUserDetail();
      console.log('需要登录，更新用户信息'); //
    }

    pubsub.subscribe('setLanguage', d => {
      this.setState({ keyid: util.randomID() });
    });
  }

  componentWillUnmount() {
    pubsub.unsubscribe('setLanguage');
  }

  render() {
    return (
      <ConfigProvider>
        <Router ref={this.routerRef} basename={config.basename} key={this.state.keyid}>
          <Switch>
            <Redirect exact from="/" to="/home" />
            {routes.map((route, index) => (
              <Route
                key={index}
                path={route.path}
                exact={route.exact} // exact的值为bool型，为true时表示严格匹配，为false时为正常匹配
                render={props => <route.component {...props} routes={route.routes} parentRoute={route} />}
              />
            ))}
          </Switch>
        </Router>
      </ConfigProvider>
    );
  }
}

export default Routers;
